# -*- coding: utf-8 -*-

"""
发送邮件
"""
import os
import re
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from buss_api.config_tools import ConfigTools
from utils.file_utils import FileUtils
from utils.icloudp_log import IcloudpLog


class SendMail(object):
    smtp_server = ""
    smtp_port = ""
    sender = ""
    pwd = ""

    @classmethod
    def get_config_info(cls):
        SendMail.smtp_server = ConfigTools.get_value("mail", "smtpserver")
        SendMail.smtp_port = ConfigTools.get_value("mail", "smtpport")
        SendMail.sender = ConfigTools.get_value("mail", "sender")
        SendMail.pwd = ConfigTools.get_value("mail", "pwd")

    @classmethod
    def send_mail_html(cls, recvs, cc, attachs, content="请查看邮件，谢谢", topic="请接收"):
        """
        邮件发送
        :param recvs:  接收人  多个接收人用逗号分隔
        :param cc:   抄送人
        :param topic:  主题
        :param content:  内容
        :param attachs: 附件, 多个附件用逗号分隔
        :return:
        """
        if not recvs:
            raise Exception("接收人不存在")
        SendMail.get_config_info()
        receiver_email = re.split(r'[, ，_;-]', recvs)
        # 创建邮件内容
        subject = topic
        content = content if content is not None else '请查看邮件，谢谢'
        body = f"""
                <blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;">
                <blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;">
                    <p>
                        <font size="4">
                            {content}
                        </font>
                    </p>
                </blockquote>
            """
        message = MIMEMultipart()
        message['Subject'] = subject
        message['From'] = SendMail.sender
        message['To'] = ','.join(receiver_email)
        cc_email = None
        if cc is not None:
            message['Cc'] = cc
            cc_email = cc.split(',')
        # 添加邮件正文
        message.attach(MIMEText(body, 'html'))

        # 添加附件
        if attachs:
            files_path = re.split(r'[, ，_;-]', attachs)
            for path in files_path:
                file_path = f'{path}'
                if FileUtils.file_exists(file_path):
                    file_name = os.path.basename(file_path)  # 只获取文件名
                    with open(file_path, 'rb') as f:
                        part = MIMEApplication(f.read(), Name=file_name)
                        part['Content-Disposition'] = f'attachment; filename="{file_path}"'
                        message.attach(part)
        #IcloudpLog.get_logger_common().info(f"smtp={SendMail.smtp_server}, port={SendMail.smtp_port}, send={SendMail.sender}, pwd={SendMail.pwd}")
        smtp = smtplib.SMTP(SendMail.smtp_server, SendMail.smtp_port)
        smtp.starttls()  # 开启TLS加密连接
        smtp.login(SendMail.sender, SendMail.pwd)
        if cc_email is None:
            smtp.sendmail(SendMail.sender, receiver_email, message.as_string())
        else:
            receiver_email.extend(cc_email)
            smtp.sendmail(SendMail.sender, receiver_email, message.as_string())


if __name__ == '__main__':
    print("Python")
